package org.gm.mybatis.generator.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.dom4j.DocumentHelper;

public class SqlExtOptional {
	public static void createUpdateFromMapByExample(StringBuilder updateSql){
		try{
			org.dom4j.Document udoc = DocumentHelper.parseText(updateSql.toString());
			org.dom4j.Element root = udoc.getRootElement();
			udoc.getRootElement().addAttribute("id", "updateFromMapByExample");
			
			org.dom4j.Element set = root.element("set");
			
			@SuppressWarnings("unchecked")
			java.util.Iterator<org.dom4j.Element> elements = set.elementIterator("if");
			while(elements.hasNext()){
				org.dom4j.Element element = elements.next();
				set.remove(element);
				org.dom4j.Element ne = set.addElement("if");
				String test = element.attributeValue("test");
				test = test.split(" ")[0];

				String[] txt = test.split("\\.");
				test = txt[0].concat(".containsKey('").concat(txt[1]).concat("')");
				ne.addAttribute("test", test);
				
				ne.add(element);
				
				org.dom4j.Element nulle = ne.addElement("if");
				
				test = element.attributeValue("test");
				test = test.replace("!=", "==");
				nulle.addAttribute("test", test);
				String text = element.getText();
				text = text.split(" = ")[0];
				text = text.concat("=null,");
				nulle.setText(text);
			}
			updateSql.replace(0, updateSql.length(), "");
			updateSql.append(udoc.asXML().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ""));
			ByteArrayInputStream inStream = new ByteArrayInputStream(updateSql.toString().getBytes());
			InputStreamReader inStreamReader = new InputStreamReader(inStream);
			BufferedReader bufferedReader = new BufferedReader(inStreamReader);
			ByteArrayOutputStream oStream = new ByteArrayOutputStream();
			OutputStreamWriter outStreamWriter = new OutputStreamWriter(oStream);
			BufferedWriter bufferedWriter = new BufferedWriter(outStreamWriter);
			String buffer = null;
			while((buffer=bufferedReader.readLine())!=null){
				if(buffer.trim().length()>0){
					bufferedWriter.write(buffer);
				}
			}
			bufferedWriter.flush();
			updateSql.replace(0, updateSql.length(), "");
			updateSql.append(oStream.toString());
			
			inStream.close();
			oStream.close();
		}catch(Exception ex){
			ex.toString();
		}
	}
}
